#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>

#include <stdio.h>
#include <string.h>

#define BSZ (32*1024)

char buf[BSZ];

//---------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
//---------------------------------------------------------------------------------
    if(argc<4) {
        printf("usage %s <file> <dest file> <ip>\n",argv[0]);
        return 0;
    }

    char *sfname = argv[1];
    char *dfname = argv[2];
    char *ip = argv[3];

    FILE *f = fopen(sfname, "rb");
    fseek(f, 0, SEEK_END);
    unsigned int fsz = ftell(f);
    fseek(f, 0, SEEK_SET);


    int sock = socket( AF_INET, SOCK_STREAM, 0 );
    printf("Created Socket!\n");

    // Tell the socket to connect to the IP address we found, on port 80 (HTTP)
    struct sockaddr_in sain;
    sain.sin_family = AF_INET;
    sain.sin_port = htons(80);
    sain.sin_addr.s_addr = inet_addr(ip);

    if(connect( sock,(struct sockaddr *)&sain, sizeof(sain) )==-1) {
        printf("connection error\n");
        return 0;
    }

    printf("Connected to server!\n");

    write(sock, dfname, strlen(dfname)+1);
    int i;
    for(i=0;i<4;i++) {
        unsigned char b = (fsz>>(8*i)) & 0xFF;
        write(sock,&b,1);
    }

    unsigned long t0 = time(0);
    unsigned long t1 = t0;
    unsigned int total=0;
    while(!feof(f)) {
        unsigned long t2 = time(0);
        int rdlen = fread(buf,1,BSZ,f);
        total += rdlen;
        if(t1!=t2) {
            printf("enviando %d of %d (%d%%) %d kbps\n",total,fsz,(total*100)/fsz,total/((t2-t0)*1024) );
            t1=t2;
        }
        write(sock,buf,rdlen);
    }
    fclose(f);

    printf("esperando confirmacao\n");
    read(sock, buf,4096);
    printf("done!\n");

    close(sock);

    return 0;
}
